package app.htby.utils;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * 上下文获取工具类
 *
 */
public class SpringContextUtil {
	private static ConfigurableApplicationContext applicationContext;

    private static BeanDefinitionRegistry beanDefinitionRegistry;

	public static void setConfigurable(ConfigurableApplicationContext context) {
		applicationContext = context;
		beanDefinitionRegistry = (DefaultListableBeanFactory) context.getBeanFactory();
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String beanId) {
		return applicationContext.getBean(beanId);
	}
	
	/**
	 * 注册bean
	 * 
	 * @param beanId
	 *            所注册bean的id
	 * @param className
	 *            bean的className， 三种获取方式：
	 *            1、直接书写，如：com.mvc.entity.User
	 *            2、User.class.getName 3.user.getClass().getName()
	 */
	public static void registerBean(String beanId, String className) {
		// get the BeanDefinitionBuilder
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(className);
		// get the BeanDefinition
		BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
		// register the bean
		if(beanDefinitionRegistry == null) {
			//如果没拿到，等待两秒重新拿去
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		beanDefinitionRegistry.registerBeanDefinition(beanId, beanDefinition);
	}
	
	/**
     * 移除bean
     * @param beanId bean的id
     */
    public static void unregisterBean(String beanId){
        beanDefinitionRegistry.removeBeanDefinition(beanId);
    }
}
